package com.woniuxy.yygh.msm.controller;

import com.woniuxy.yygh.common.result.Result;
import com.woniuxy.yygh.msm.service.FileService;
import com.woniuxy.yygh.msm.service.MsmService;
import com.woniuxy.yygh.msm.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.concurrent.TimeUnit;

/**
 * <P> @Author: ideaAdmin
 * <P> TODO: Class
 * <P> TODO: 短信和上传服务
 * <P> Date: 2022/3/3:20:36
 * <P> Description:
 */
@RestController
@RequestMapping("/api/msm")
public class MsmController {
    @Autowired
    MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private FileService fileService;

    /**
        * TODO:接收号码发送验证码
    **/
    @GetMapping("/send/{phone}")
    public Result sendCode(@PathVariable String phone){

        //从redis获取验证码 如果获取到 返回ok
        //key 手机号 value 验证码
        String code = redisTemplate.opsForValue().get(phone);

        if(!StringUtils.isEmpty(code)){
            return Result.ok();
        }
        //如果获取不到 生成整合短信服务进行发送
        //生成验证码
        code = RandomUtil.getSixBitRandom();

       boolean isSend = msmService.send(phone,code);
        //TODO boolean isSend = true;
        if(isSend){
            redisTemplate.opsForValue().set(phone,code,129600, TimeUnit.MINUTES);
            return Result.ok();
        }else {
            return Result.fail().message("发送短信失败");
        }
    }

    /**
        * TODO:上传文件到 oss
    **/
    @PostMapping("/fileUpload")
    public Result fileUpload(MultipartFile file){

        //获取上传文件路径
        String url = fileService.upload(file);
        return Result.ok(url);
    }
}
